import {
  dynamicList,
  dynamicEndorse
} from "../../api/index"
import {timeFormat} from "../../utils/util"
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading:false,
    dynamicList: [],
    CustomBar: app.globalData.CustomBar,
    content: '' // 模糊搜索动态内容
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.getDynamicList()
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {


  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  clickIntoDetail:function(e){
    //进入动态详情页
    let id = e.currentTarget.dataset.item._id
    wx.navigateTo({
      url: `/pages/dynamicDetail/dynamicDetail?dynamicId=${id}`,
    })
  },
  editDynamic: function () {
    //点击进入动态编辑页面
    wx.navigateTo({
      url: '/pages/dynamicPublish/dynamicPublish',
    })
  },
  getDynamicList: async function () {
    this.setData({
      loading:true
    })
    let result = await dynamicList({
      page: 1,
      number: 10
    })
    if (result) {
      for(let i in result.data){
        result.data[i].createTime = timeFormat(result.data[i].createTime)
      }
      this.setData({
        dynamicList: result.data,
        loading:false
      })
    }
    console.log(result)
  },
  endorseClick: async function(e){
    let dynamic = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index
    const result = await dynamicEndorse({dynamicId:dynamic._id,active:dynamic.isEndorse===1?0:1})
    if(result){
      this.setData({
        [`dynamicList[${index}].endorseCount`]:dynamic.isEndorse===1?dynamic.endorseCount-1:dynamic.endorseCount+1,
        [`dynamicList[${index}].isEndorse`]:dynamic.isEndorse===1?0:1
      })
    }
  },
  previewImg:function(e){
    //预览图片
    let index = e.currentTarget.dataset.index
    let images = e.currentTarget.dataset.item.images
    wx.previewImage({
      current:images[index],
      urls: images,
    }) 
  }
})